﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Phatent.Model.Functions;
using Phatent.Model;
namespace Phatent.Command.Functions
{
    public class EmployeeCommand
    {
        public static EmployeeModel GetModel(Guid guid)
        {
            if (guid != Guid.Empty)
            {
                using (DBCentre db = new DBCentre())
                {
                    var d = db.DataContext.Employees.FirstOrDefault(p => p.Guid == guid);
                    if (d != null)
                    {
                        var ret = Convertor.ConvertTo<EmployeeModel, Employee>(d);
                        return ret;
                    }
                }
            }
            return null;
        }

        public static EmployeeCollection Gets(QueryBase sea)
        {
            var ret = new EmployeeCollection();
            using (DBCentre db = new DBCentre())
            {
                IQueryable<Employee> q = db.DataContext.Employees;
                var n = q.Count();
                if (n > 0)
                {
                    q = q.OrderByDescending(p => p.CreatedOn);
                    if (sea != null && sea.PageSize > 0)
                        q = q.Skip(sea.PageSize * sea.PageIndex).Take(sea.PageSize);
                    var lst = q.ToList();
                    ret = Convertor.ConvertCollection<EmployeeModel, Employee, EmployeeCollection>(lst);
                    ret.TotalRecordsCount = n;
                }
            }
            return ret;
        }

        public static EmployeeModel CreateNew(EmployeeModel model)
        {
            if (model != null)
            {
                model.Guid = Guid.NewGuid();
                model.CreatedOn = DateTime.Now;
                model.Status = 1;
                using (DBCentre db = new DBCentre())
                {
                    var d = Convertor.ConvertFrom<Employee, EmployeeModel>(model);
                    db.DataContext.Employees.Add(d);
                    db.DataContext.SaveChanges();
                }
                return model;
            }
            return null;
        }

        public static void Expired(Guid guid)
        {
            if (guid != Guid.Empty)
            {
                using (DBCentre db = new DBCentre())
                {
                    var d = db.DataContext.Employees.FirstOrDefault(p => p.Guid == guid);
                    if (d != null)
                    {
                        d.Status = 0;
                        db.DataContext.SaveChanges();
                    }
                }
            }
        }
    }
}
